<!DOCTYPE html>
<html lang="en" style="font-size: 2vw;">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .flex {
            display: flex;
            flex-wrap: wrap;
        }

        .flex > div {
            border: solid 1px #ccc;
            padding: .5rem;
            line-height: 1.6;
            margin: .5rem;
        }
    </style>
</head>
<body>
<div class="flex">


</div>
<div>
    <a href="inc.jsp">inc.jsp</a>
    <button>ajax</button>
    <button>异步10次</button>
    <button>同步10次</button>
    <button>异步顺序10次</button>
</div>
<script>
    let obj = document.querySelector(".flex");
    let btns = document.querySelectorAll("button");
    let ajax1 = function () {
        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            console.debug(`readyState:${xhr.readyState}, status:${xhr.status}`);
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    console.debug(xhr.responseText);
                    obj.innerHTML += xhr.responseText;
                } else {
                    console.warn(`ajax请求失败,状态码:${xhr.status},错误消息:${xhr.statusText}`);
                }
            }
        }
        xhr.open("GET", "inc.jsp?name=ajax1");
        xhr.setRequestHeader("a", "b");//设置请求头
        xhr.send();//发送请求
    }

    btns[0].onclick = ajax1;


    /**
     *
     * @param num - name参数值
     * @param async - 是否异步
     */
    let ajax2 = function (num=0,async=true) {
        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    obj.innerHTML += xhr.responseText;
                } else {
                    console.warn(`ajax请求失败,状态码:${xhr.status},错误消息:${xhr.statusText}`);
                }
            }
        }
        xhr.open("GET", "inc.jsp?name="+num,async);
        xhr.send();//发送请求
    }

    //异步10次
    btns[1].onclick = function () {
        for(let i=0;i<10;i++){
            ajax2(i,true);
        }
    }

    //同步10次
    btns[2].onclick = function () {
        for(let i=0;i<10;i++){
            ajax2(i,false);
        }
    }

    //ajax编程尽量使用异步
    //?怎么样异步有序执行呢?
    let ajax3 = function (num=0) {
        if(num==10){
            return;
        }
        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    obj.innerHTML += xhr.responseText;
                    ajax3(++num);
                } else {
                    console.warn(`ajax请求失败,状态码:${xhr.status},错误消息:${xhr.statusText}`);
                }
            }
        }
        xhr.open("GET", "inc.jsp?name="+num);
        xhr.send();//发送请求
    }
    btns[3].onclick = function () {
        ajax3(0);
    }



</script>
</body>
</html>